/*
 * Gmail Reader (GMan -- The Gmail Postman)
 * 
 * This application creates your own Gmail Notifier kind of application that checks the new mails using recently 
 * introduced Gmail Atom Feeds and speaks the details of the mail using Microsoft Agent.
 * 
 * Author: Anup Shinde
 * Email:  anup@micromacs.com
 * 
 * */

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text;

namespace GMReader
{
	/// <summary>
	/// Summary description for frmMain.
	/// </summary>
	public class frmMain : System.Windows.Forms.Form
	{

		//Check if the Agent is Loaded correctly.
		private bool IsAgentLoaded=false;

		private bool IsClosing=false;

		private AgentObjects.IAgentCtlCharacterEx agentRef;
		private System.Windows.Forms.MenuItem mnuConnection;
		private System.Windows.Forms.MenuItem mnuProxySettings;
		private System.Windows.Forms.MenuItem mnuShowHide;
		private System.Windows.Forms.MenuItem mnuExit;
		private System.Windows.Forms.MenuItem mnuHideCharacter;
		private System.Windows.Forms.MenuItem mnuCloseMenu;
		private System.Windows.Forms.ContextMenu cmnuMain;
		internal System.Windows.Forms.Label Label1;
		internal System.Windows.Forms.TextBox txtUserPassword;
		internal System.Windows.Forms.TextBox txtUserName;
		internal System.Windows.Forms.CheckBox chkRememberMe;
		internal System.Windows.Forms.Button cmdOK;
		internal System.Windows.Forms.Label Label3;

		private String  last_accessed_DateTime = "01-Jan-1900 00:00:00";
		private System.Windows.Forms.MenuItem mnuCheckMail;
		private System.Windows.Forms.Timer tmrCheckMail;
		private System.Windows.Forms.MenuItem mnuAgent;
		private System.Windows.Forms.MenuItem mnuMerlin;
		private System.Windows.Forms.MenuItem mnuPeedy;
		private System.Windows.Forms.MenuItem mnuRobby;
		private System.Windows.Forms.MenuItem mnuGenie;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem mnuAbout;
		private System.Windows.Forms.MenuItem mnuAnup;
		private AxAgentObjects.AxAgent agentMain;
		private System.ComponentModel.IContainer components;

		public frmMain()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmMain));
			this.mnuConnection = new System.Windows.Forms.MenuItem();
			this.mnuProxySettings = new System.Windows.Forms.MenuItem();
			this.mnuShowHide = new System.Windows.Forms.MenuItem();
			this.mnuExit = new System.Windows.Forms.MenuItem();
			this.mnuHideCharacter = new System.Windows.Forms.MenuItem();
			this.mnuCloseMenu = new System.Windows.Forms.MenuItem();
			this.cmnuMain = new System.Windows.Forms.ContextMenu();
			this.mnuAgent = new System.Windows.Forms.MenuItem();
			this.mnuMerlin = new System.Windows.Forms.MenuItem();
			this.mnuPeedy = new System.Windows.Forms.MenuItem();
			this.mnuRobby = new System.Windows.Forms.MenuItem();
			this.mnuGenie = new System.Windows.Forms.MenuItem();
			this.mnuAnup = new System.Windows.Forms.MenuItem();
			this.mnuCheckMail = new System.Windows.Forms.MenuItem();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.mnuAbout = new System.Windows.Forms.MenuItem();
			this.Label1 = new System.Windows.Forms.Label();
			this.txtUserPassword = new System.Windows.Forms.TextBox();
			this.txtUserName = new System.Windows.Forms.TextBox();
			this.chkRememberMe = new System.Windows.Forms.CheckBox();
			this.cmdOK = new System.Windows.Forms.Button();
			this.Label3 = new System.Windows.Forms.Label();
			this.tmrCheckMail = new System.Windows.Forms.Timer(this.components);
			this.agentMain = new AxAgentObjects.AxAgent();
			((System.ComponentModel.ISupportInitialize)(this.agentMain)).BeginInit();
			this.SuspendLayout();
			// 
			// mnuConnection
			// 
			this.mnuConnection.Index = 4;
			this.mnuConnection.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						  this.mnuProxySettings});
			this.mnuConnection.Text = "Connection";
			// 
			// mnuProxySettings
			// 
			this.mnuProxySettings.Index = 0;
			this.mnuProxySettings.Text = "Proxy Settings";
			this.mnuProxySettings.Click += new System.EventHandler(this.mnuProxySettings_Click);
			// 
			// mnuShowHide
			// 
			this.mnuShowHide.Index = 3;
			this.mnuShowHide.Text = "Hide Window";
			this.mnuShowHide.Click += new System.EventHandler(this.mnuShowHide_Click);
			// 
			// mnuExit
			// 
			this.mnuExit.Index = 6;
			this.mnuExit.Text = "Exit";
			this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click);
			// 
			// mnuHideCharacter
			// 
			this.mnuHideCharacter.Index = 0;
			this.mnuHideCharacter.Text = "Hide";
			this.mnuHideCharacter.Click += new System.EventHandler(this.mnuHideCharacter_Click);
			// 
			// mnuCloseMenu
			// 
			this.mnuCloseMenu.Index = 5;
			this.mnuCloseMenu.Text = "Close Menu";
			this.mnuCloseMenu.Click += new System.EventHandler(this.mnuCloseMenu_Click);
			// 
			// cmnuMain
			// 
			this.cmnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.mnuHideCharacter,
																					 this.mnuAgent,
																					 this.mnuCheckMail,
																					 this.mnuShowHide,
																					 this.mnuConnection,
																					 this.mnuCloseMenu,
																					 this.mnuExit,
																					 this.menuItem1,
																					 this.mnuAbout});
			// 
			// mnuAgent
			// 
			this.mnuAgent.Index = 1;
			this.mnuAgent.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.mnuMerlin,
																					 this.mnuPeedy,
																					 this.mnuRobby,
																					 this.mnuGenie,
																					 this.mnuAnup});
			this.mnuAgent.Text = "Agent";
			// 
			// mnuMerlin
			// 
			this.mnuMerlin.Index = 0;
			this.mnuMerlin.Text = "Merlin";
			this.mnuMerlin.Click += new System.EventHandler(this.mnuMerlin_Click);
			// 
			// mnuPeedy
			// 
			this.mnuPeedy.Index = 1;
			this.mnuPeedy.Text = "Peedy";
			this.mnuPeedy.Click += new System.EventHandler(this.mnuPeedy_Click);
			// 
			// mnuRobby
			// 
			this.mnuRobby.Index = 2;
			this.mnuRobby.Text = "Robby";
			this.mnuRobby.Click += new System.EventHandler(this.mnuRobby_Click);
			// 
			// mnuGenie
			// 
			this.mnuGenie.Index = 3;
			this.mnuGenie.Text = "Genie";
			this.mnuGenie.Click += new System.EventHandler(this.mnuGenie_Click);
			// 
			// mnuAnup
			// 
			this.mnuAnup.Index = 4;
			this.mnuAnup.Text = "Anup";
			this.mnuAnup.Click += new System.EventHandler(this.mnuAnup_Click);
			// 
			// mnuCheckMail
			// 
			this.mnuCheckMail.Index = 2;
			this.mnuCheckMail.Text = "Check Mail Now";
			this.mnuCheckMail.Click += new System.EventHandler(this.mnuCheckMail_Click);
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 7;
			this.menuItem1.Text = "-";
			// 
			// mnuAbout
			// 
			this.mnuAbout.Index = 8;
			this.mnuAbout.Text = "About";
			this.mnuAbout.Click += new System.EventHandler(this.mnuAbout_Click);
			// 
			// Label1
			// 
			this.Label1.AutoSize = true;
			this.Label1.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.Label1.ForeColor = System.Drawing.Color.Navy;
			this.Label1.Location = new System.Drawing.Point(8, 8);
			this.Label1.Name = "Label1";
			this.Label1.Size = new System.Drawing.Size(63, 16);
			this.Label1.TabIndex = 21;
			this.Label1.Text = "User Name";
			// 
			// txtUserPassword
			// 
			this.txtUserPassword.AutoSize = false;
			this.txtUserPassword.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.txtUserPassword.Cursor = System.Windows.Forms.Cursors.IBeam;
			this.txtUserPassword.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.txtUserPassword.Location = new System.Drawing.Point(80, 32);
			this.txtUserPassword.Name = "txtUserPassword";
			this.txtUserPassword.PasswordChar = '*';
			this.txtUserPassword.Size = new System.Drawing.Size(128, 20);
			this.txtUserPassword.TabIndex = 22;
			this.txtUserPassword.Text = "";
			// 
			// txtUserName
			// 
			this.txtUserName.AutoSize = false;
			this.txtUserName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.txtUserName.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.txtUserName.Location = new System.Drawing.Point(80, 8);
			this.txtUserName.Name = "txtUserName";
			this.txtUserName.Size = new System.Drawing.Size(128, 20);
			this.txtUserName.TabIndex = 20;
			this.txtUserName.Text = "";
			// 
			// chkRememberMe
			// 
			this.chkRememberMe.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.chkRememberMe.ForeColor = System.Drawing.Color.Navy;
			this.chkRememberMe.Location = new System.Drawing.Point(88, 64);
			this.chkRememberMe.Name = "chkRememberMe";
			this.chkRememberMe.Size = new System.Drawing.Size(112, 24);
			this.chkRememberMe.TabIndex = 26;
			this.chkRememberMe.Text = "&Remember me";
			this.chkRememberMe.CheckedChanged += new System.EventHandler(this.chkRememberMe_CheckedChanged);
			// 
			// cmdOK
			// 
			this.cmdOK.DialogResult = System.Windows.Forms.DialogResult.OK;
			this.cmdOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
			this.cmdOK.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.cmdOK.ForeColor = System.Drawing.Color.Navy;
			this.cmdOK.Location = new System.Drawing.Point(16, 64);
			this.cmdOK.Name = "cmdOK";
			this.cmdOK.Size = new System.Drawing.Size(56, 24);
			this.cmdOK.TabIndex = 24;
			this.cmdOK.Text = "&Login";
			this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
			// 
			// Label3
			// 
			this.Label3.AutoSize = true;
			this.Label3.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.Label3.ForeColor = System.Drawing.Color.Navy;
			this.Label3.Location = new System.Drawing.Point(8, 32);
			this.Label3.Name = "Label3";
			this.Label3.Size = new System.Drawing.Size(58, 16);
			this.Label3.TabIndex = 23;
			this.Label3.Text = "Password";
			// 
			// tmrCheckMail
			// 
			this.tmrCheckMail.Tick += new System.EventHandler(this.tmrCheckMail_Tick);
			// 
			// agentMain
			// 
			this.agentMain.Enabled = true;
			this.agentMain.Location = new System.Drawing.Point(24, 16);
			this.agentMain.Name = "agentMain";
			this.agentMain.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("agentMain.OcxState")));
			this.agentMain.Size = new System.Drawing.Size(32, 32);
			this.agentMain.TabIndex = 27;
			this.agentMain.ClickEvent += new AxAgentObjects._AgentEvents_ClickEventHandler(this.agentMain_ClickEvent);
			// 
			// frmMain
			// 
			this.AcceptButton = this.cmdOK;
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.BackColor = System.Drawing.Color.WhiteSmoke;
			this.ClientSize = new System.Drawing.Size(218, 98);
			this.Controls.Add(this.agentMain);
			this.Controls.Add(this.Label1);
			this.Controls.Add(this.txtUserPassword);
			this.Controls.Add(this.txtUserName);
			this.Controls.Add(this.Label3);
			this.Controls.Add(this.chkRememberMe);
			this.Controls.Add(this.cmdOK);
			this.ForeColor = System.Drawing.SystemColors.ControlText;
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
			this.MaximizeBox = false;
			this.Name = "frmMain";
			this.ShowInTaskbar = false;
			this.Text = "GMan Login";
			this.Closing += new System.ComponentModel.CancelEventHandler(this.frmMain_Closing);
			this.Load += new System.EventHandler(this.frmMain_Load);
			((System.ComponentModel.ISupportInitialize)(this.agentMain)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion


		private void frmMain_Load(object sender, System.EventArgs e)
		{

			// Set the timer interval to 5 minutes
			tmrCheckMail.Interval = (int)(5*1000*60);

			// Load the saved configuration.
			clsMain.ReadOptions();

			txtUserName.Text = clsMain.g_GMUserName;
			txtUserPassword.Text = clsMain.g_GMUserPass;
			chkRememberMe.Checked = clsMain.g_SaveGMPass;

			// Load the Microsoft Agent character.
			LoadAgent(clsMain.g_AgentFileName);

			// If the password is saved, login using the saved username and password.
			if(clsMain.g_SaveGMPass)
			{
				this.cmdOK_Click(sender,e);
			}

		}


		// Re-initialize the Last Accessed DateTime and check the mails
		private void cmdOK_Click(object sender, System.EventArgs e)
		{
			last_accessed_DateTime = "01-Jan-1900 00:00:00";
			CheckMailNow();		
//			tmrCheckMail.Enabled=true;
		}


		/// <summary>
		/// Check the mails
		/// </summary>
		private void CheckMailNow()
		{
			tmrCheckMail.Enabled=false;
			byte[] bytes;
			WebRequest wrGETURL=null;

			// Check if the user has opted to remember username and password. If Yes, save those.
			RememberMeCheckedChanged();

			try
			{
				// Create a new web-request instance
				wrGETURL = WebRequest.Create(clsMain.g_GMServerURL);

				// If a proxy is required, set it
				if(clsMain.g_UseProxy)
				{
					wrGETURL.Proxy = clsMain.GetProxy();
				}

				// NOTE: Do not use g_GMUserName, as those would not be stored in case RememberMe is unchecked.
				bytes = Encoding.ASCII.GetBytes(txtUserName.Text.Trim() + ":" + txtUserPassword.Text.Trim());

				// Add the headers for basic authentication.
				wrGETURL.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
			}
			catch(Exception ex1)
			{
				//MessageBox.Show("Oops..." + ex1.Message,"Error",System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Error);
				agentRef.Show(false);
				agentRef.Speak("Oops. Some error occurred. " + ex1.Message,"");
			}

			try
			{
				String FromName, Title, Content;

				// Get the response feed
				Stream feedStream =	wrGETURL.GetResponse().GetResponseStream();

				
				string strTemp = "";
				string spkTitle="";
				string strFeedTime="";
				DateTime feedTime;
				DateTime entfeedTime;


				Atom.Core.AtomFeed myFeed;
				try
				{
					myFeed = Atom.Core.AtomFeed.Load(feedStream);
					strFeedTime = myFeed.Modified.DateTime.Day.ToString() + "-" + myFeed.Modified.DateTime.ToString("MMM") + "-" + myFeed.Modified.DateTime.Year.ToString() + " " +  myFeed.Modified.DateTime.TimeOfDay.ToString();
					feedTime= DateTime.Parse(strFeedTime);

					// If the feed has not been modified since last accessed time, no need to notify the user
					if( feedTime <= DateTime.Parse(last_accessed_DateTime))
					{
						tmrCheckMail.Enabled=true;
						return;
					}
				}
				catch(Exception ex)
				{
					String err = ex.Message;
					agentRef.Show(false);
					agentRef.Speak("Oops. Some error occurred while reading mails","");
					tmrCheckMail.Enabled=true;
					return;
				}

				Atom.Core.Collections.AtomEntryCollection ents = myFeed.Entries;

				if(ents.Count>0)
				{
					// Show the agent and notify the user

					agentRef.Show(false);
					
					strTemp+= " You have got new mail";
					//The following displays the invalid count (only 20 feeds arrived, while uncheckd mails are much more than that)
					//strTemp+= " You have got " + ents.Count.ToString() + " new mail";

					if(ents.Count>1)
					{
						strTemp+="s";
					}
					agentRef.Speak(strTemp,"");
					System.Threading.Thread.Sleep(300);
				}



				strTemp="";
				int max_reads = 10;
				int i = 0;
				
				foreach(Atom.Core.AtomEntry ent in ents)
				{
					if(i>=max_reads) break;
					FromName = ent.Author.Name;
					Title = ent.Title.Content;
					Content = ent.Summary.Content;

					// Notify about the new feeds only.

					strFeedTime = ent.Modified.DateTime.Day.ToString() + "-" + ent.Modified.DateTime.ToString("MMM") + "-" + ent.Modified.DateTime.Year.ToString() + " " +  ent.Modified.DateTime.TimeOfDay.ToString();
					entfeedTime= DateTime.Parse(strFeedTime);
					if(entfeedTime <= DateTime.Parse(last_accessed_DateTime))
					{
						strTemp="";
						i++;
						continue;
					}

					// Create a more user-friendly voice for the mail index
					strTemp= " The " + DescNum(ents.IndexOf(ent)+1) + " mail is from " + FromName + ". ";
					agentRef.Speak(strTemp,"");


					// Create a more user-friendly voice, if the mail is a Reply or Forward.
					strTemp= "";
					if(Title.Trim().ToUpper().Substring(0,3) == "RE:")
					{
						//Donot modify case here, as it affects the way the words are spoken
						spkTitle = Title.Trim();
						spkTitle = spkTitle.Replace("RE:"," ");
						spkTitle = spkTitle.Replace("Re:"," ");
						spkTitle = spkTitle.Replace("rE:"," ");
						spkTitle = spkTitle.Replace("re:"," ");
						spkTitle = spkTitle.Trim();
						strTemp+= " It is a reply regarding " + spkTitle;
					}
					else if(Title.Trim().ToUpper().Substring(0,4) == "FWD:")
					{
						//Donot modify case here, as it affects the way the words are spoken
						spkTitle = Title.Trim();
						spkTitle = spkTitle.Replace("fwd:"," ");
						spkTitle = spkTitle.Replace("fwD:"," ");
						spkTitle = spkTitle.Replace("fWd:"," ");
						spkTitle = spkTitle.Replace("fWD:"," ");
						spkTitle = spkTitle.Replace("Fwd:"," ");
						spkTitle = spkTitle.Replace("FwD:"," ");
						spkTitle = spkTitle.Replace("FWd:"," ");
						spkTitle = spkTitle.Replace("FWD:"," ");
						spkTitle = spkTitle.Trim();
						strTemp+= " It is a forward regarding " + spkTitle;
					}
					else
					{
						spkTitle = Title.Trim();
						strTemp+= " It is regarding " + spkTitle;
					}
					agentRef.Speak(strTemp,"");

					System.Threading.Thread.Sleep(100);

					strTemp="";
					i++;
				}

				feedStream.Close();
				
				// Set the last accessed time to the latest one.
				last_accessed_DateTime = feedTime.Day.ToString() + "-" + feedTime.ToString("MMM") + "-" + feedTime.Year.ToString() + " " +  feedTime.TimeOfDay.ToString();

				this.ShowHide(true);
			}
			catch(Exception ex)
			{
				String err = ex.Message;
				agentRef.Show(false);
				agentRef.Speak("Oops. I cannot connect to GMail server","");
				//MessageBox.Show("Oops...cannot connect to GMail server","Error",System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Error);
			}

			agentRef.Hide(false);
			tmrCheckMail.Enabled=true;
		}


		/// <summary>
		/// Convert the input integer to its speakable string. i.e. 1 to 1st, 2 to 2nd
		/// </summary>
		/// <param name="numIn">Input number</param>
		/// <returns>Output string</returns>
		public string DescNum(int numIn)
		{
			string ret_val;

			int n = numIn%100;
			if(n > 10 && n<20)
			{
				ret_val=numIn.ToString() + "th";
			}
			else
			{
				n = numIn%10;
				string[] arrS = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
				ret_val = numIn.ToString() +  arrS[n];
			}

			return ret_val;
		}

		private void chkRememberMe_CheckedChanged(object sender, System.EventArgs e)
		{
			RememberMeCheckedChanged();
		}

		/// <summary>
		///  Save the username and password in the config file, if opted for.
		/// </summary>
		private void RememberMeCheckedChanged()
		{
			if(chkRememberMe.Checked)
			{
				clsMain.g_GMUserName=txtUserName.Text.Trim();
				clsMain.g_GMUserPass=txtUserPassword.Text.Trim();
			}
			else
			{
				clsMain.g_GMUserName="";
				clsMain.g_GMUserPass="";
			}

			clsMain.g_SaveGMPass = chkRememberMe.Checked;

			clsMain.WriteOptions();
		}


		/// <summary>
		/// Handle the click event so that we can show a custom menu, when the agent is right-clicked.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void agentMain_ClickEvent(object sender, AxAgentObjects._AgentEvents_ClickEvent e)
		{
			this.BringToFront();
			//this.Focus();
			if(e.button == 2)
			{
	            Point pnt = new Point(e.x - this.Left, e.y - this.Top);
		        cmnuMain.Show(this, pnt);
			}
		}

		private void mnuShowHide_Click(object sender, System.EventArgs e)
		{
			ShowHide();
		}

		/// <summary>
		///  ShowHide with optional parameter
		/// </summary>

		private void ShowHide()
		{
			ShowHide(false);
		}

		/// <summary>
		/// Make the form completely transparent. Calling the Hide method would make the ContextMenu invisible.
		/// </summary>
		/// <param name="IsCompulsoryHide"></param>
		private void ShowHide(bool IsCompulsoryHide)
		{
			if(IsCompulsoryHide)
			{
				this.Opacity = 0;
				mnuShowHide.Text= "Show Window";
			}
			else
			{
				this.Opacity = Math.Abs(this.Opacity-1.0);
				mnuShowHide.Text= (this.Opacity>0)?"Hide Window":"Show Window";
				this.Focus();
			}
		}

		private void mnuHideCharacter_Click(object sender, System.EventArgs e)
		{
			agentRef.StopAll(null);
			agentRef.Hide(false);
		}

		private void mnuCloseMenu_Click(object sender, System.EventArgs e)
		{
			//Do nothing
		}

		private void mnuExit_Click(object sender, System.EventArgs e)
		{
			IsClosing=true;
			this.Close();
		}

		private void mnuProxySettings_Click(object sender, System.EventArgs e)
		{
			frmProxyConfigure frmPxy  = new frmProxyConfigure();
			frmPxy.ShowDialog();
		}

		private void mnuCheckMail_Click(object sender, System.EventArgs e)
		{
			CheckMailNow();		
		}

		private void tmrCheckMail_Tick(object sender, System.EventArgs e)
		{
			CheckMailNow();		
		}


		/// <summary>
		/// Load the Character in the Agent, specified by the agentFileName
		/// </summary>
		/// <param name="agentFileName"></param>
		private void LoadAgent(String agentFileName)
		{
			try
			{
				try
				{
					agentRef.StopAll(null);
					agentRef.Hide(false);
					agentMain.Characters.Unload("agentAssistant");
					agentRef=null;
				}
				catch{}

				agentMain.Characters.Load("agentAssistant", agentFileName);
				agentRef = agentMain.Characters.Character("agentAssistant");
				agentRef.AutoPopupMenu = false;
				IsAgentLoaded = true;
				clsMain.g_AgentFileName=agentFileName;
				clsMain.WriteOptions();


				if (IsAgentLoaded) 
				{
					agentRef.Left = (short)(this.Left + this.Width + 10);
					agentRef.Top = (short)(this.Top + this.Height + 10);

					agentRef.Show(false);

					agentRef.Play("Greet");
					agentRef.Play("Explain");
					agentRef.Speak("Hi. I will be fetching your Google Mails","");
					agentRef.Play("Acknowledge");
					agentRef.Speak("You can activate me whenever you want.","");
					agentRef.Speak("Bye bye.","");
					agentRef.Play("Wave");
					agentRef.Hide(false);
				}


			}
			catch(Exception ex)
			{
				string strErr = ex.Message;
				MessageBox.Show("There was an error loading character. The program will be closed", "Error loading character");
				IsAgentLoaded = false;
				this.Close();
			}
		}

		private void mnuAbout_Click(object sender, System.EventArgs e)
		{
			String strTemp="";

			strTemp+="The GMan is brought to you by: \n\n";
			strTemp+="Anup Shinde, microMaCS.com \n\n";
			strTemp+="anup@micromacs.com \n\n";
			strTemp+=" \n\n";
			strTemp+="Enjoy! \n\n";
			agentRef.Show(false);
			agentRef.Speak(strTemp,"");
			//MessageBox.Show(strTemp, "About");

		}

		private void mnuMerlin_Click(object sender, System.EventArgs e)
		{
			LoadAgent("merlin.acs");
		}

		private void mnuPeedy_Click(object sender, System.EventArgs e)
		{
			LoadAgent("peedy.acs");
		}

		private void mnuRobby_Click(object sender, System.EventArgs e)
		{
			LoadAgent("robby.acs");
		}

		private void mnuGenie_Click(object sender, System.EventArgs e)
		{
			LoadAgent("genie.acs");
		}

		private void mnuAnup_Click(object sender, System.EventArgs e)
		{
			MessageBox.Show("There was an error loading character.\n Help me develop this character.\n Contact anup@micromacs.com \nThanks.", "Error loading character");
		}

		private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			ShowHide(true);
			e.Cancel=!IsClosing;
			IsClosing=false;
		}


///
///Random Animation for the character.
//////		public string RandomAnimation()
//////		{
//////			int i=0;
//////			int randm;
//////			string crrnt_ani="";
//////			System.Random rnd = new System.Random((int)DateTime.Now.Ticks);
//////			randm=rnd.Next(100);
//////			IEnumerator objEnum=agentRef.AnimationNames.GetEnumerator();
//////			while(i<=randm)
//////			{
//////				objEnum.Reset();
//////				while(objEnum.MoveNext() && i<=randm)
//////				{
//////					i++;
//////					crrnt_ani=objEnum.Current.ToString();
//////					//				MessageBox.Show(objEnum.Current.GetType().ToString());
//////				}
//////			}
//////
//////			return crrnt_ani;
//////		}

	}

}
